<template>
    <div class="login">
        <el-form class="login-form" ref="loginForm" :model="loginForm" :rules="loginRules">
            <div class="title">
                {{ title }}
            </div>
            <el-form-item prop="username">
                <el-input
                    :disabled="loading"
                    v-model="loginForm.username"
                    type="text"
                    auto-complete="off"
                    placeholder="账号"
                    clearable
                >
                    <template #prefix>
                        <el-icon><ep-User /></el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input
                    :disabled="loading"
                    v-model="loginForm.password"
                    type="password"
                    auto-complete="off"
                    placeholder="密码"
                    clearable
                >
                    <template #prefix>
                        <el-icon><ep-Lock /></el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item prop="captcha" v-if="captchaEnabled">
                <el-input
                    :disabled="loading"
                    class="inputCode"
                    style="width: 63%"
                    v-model="loginForm.captcha"
                    auto-complete="off"
                    placeholder="验证码"
                    @keyup.enter="login"
                    clearable
                >
                    <template #prefix>
                        <el-icon> <ep-CircleCheck /></el-icon>
                    </template>
                </el-input>
                <div class="login-code">
                    <img
                        class="login-code-img"
                        :src="codeUrl"
                        @click="loading ? null : getCode"
                        alt="验证码图片"
                    />
                </div>
            </el-form-item>
            <el-checkbox
                :disabled="loading"
                v-model="loginForm.rememberMe"
                label="记住密码"
                size="large"
            />
            <el-form-item>
                <el-button
                    :disabled="loading"
                    style="width: 100%"
                    size="large"
                    type="primary"
                    @click.prevent="login"
                >
                    <span v-if="!loading">登 录</span>
                    <span v-else>登 录 中...</span>
                </el-button>
            </el-form-item>
        </el-form>
        <!--  底部  -->
        <div class="el-login-footer">
            <span>Copyright ©2024 love rain All Rights Reserved.</span>
        </div>
    </div>
</template>
<script>
import { getCodeImg } from '@/api/login'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'
import useStore from '@/stores'

export default {
    name: 'Login',
    data() {
        return {
            title: import.meta.env.VITE_APP_TITLE,
            loginForm: {
                username: 'admin',
                password: 'admin123',
                rememberMe: false,
                captcha: '',
                uuid: ''
            },
            // 验证码开关
            captchaEnabled: true,
            //验证码地址
            codeUrl: '',
            //判断是否是登录中
            loading: false,
            redirect: undefined,
            loginRules: {
                //blur 失去焦点 change 数据改变
                username: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '请输入您的账号'
                    }
                ],
                password: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '请输入您的密码'
                    }
                ],
                captcha: [
                    {
                        required: true,
                        trigger: 'change',
                        message: '请输入验证码'
                    }
                ]
            }
        }
    },
    watch: {
        //监听 $route 对象的变化
        $route: {
            // 在组件实例创建时会立即调用
            handler(route) {
                //检查路由的查询参数（route.query）是否存在，并且是否存在一个名为 redirect 的查询参数。
                //如果存在，我们就将 this.redirect 设置为该查询参数的值
                //this.redirect 是组件的一个数据属性，你需要在组件的 data 函数中定义它
                this.redirect = route.query && route.query.redirect
            },
            // 强制立即执行回调
            immediate: true
        }
    },
    //生命周期钩子，在组件实例处理完所有与状态相关的选项后调用
    created() {
        this.getCode()
        this.getCookie()
    },
    methods: {
        //获取验证码
        getCode() {
            getCodeImg().then((res) => {
                //判断后端接口返回结果是否启用验证码验证
                this.captchaEnabled =
                    res.data.captchaEnabled === undefined ? true : res.data.captchaEnabled
                if (this.captchaEnabled) {
                    this.codeUrl = res.data.img
                    this.loginForm.uuid = res.data.uuid
                }
            })
        },
        //从缓存cookie中取出保存的登录信息
        getCookie() {
            const username = Cookies.get('username')
            const password = Cookies.get('password')
            const rememberMe = Cookies.get('rememberMe')
            this.loginForm = {
                username: username === undefined ? this.loginForm.username : username,
                password: password === undefined ? this.loginForm.password : decrypt(password),
                rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
            }
        },
        //登录事件
        login() {
            //使用模版引用访问form,点击提交时,整体表单校验,validate方法
            this.$refs.loginForm.validate((valid) => {
                //表单验证通过时为true
                if (valid) {
                    //更新登录按钮点击标志
                    this.loading = true
                    if (this.loginForm.rememberMe) {
                        //如果启用了记住密码，则使用cookie缓存输入的登录信息
                        Cookies.set('username', this.loginForm.username, {
                            expires: 30
                        })
                        Cookies.set('password', encrypt(this.loginForm.password), {
                            expires: 30
                        })
                        Cookies.set('rememberMe', this.loginForm.rememberMe, {
                            expires: 30
                        })
                    } else {
                        Cookies.remove('username')
                        Cookies.remove('password')
                        Cookies.remove('rememberMe')
                    }
                    const { user } = useStore()
                    const redirectPath = this.redirect ? decodeURIComponent(this.redirect) : '/'
                    user.Login(this.loginForm)
                        .then(() => {
                            //调用接口成功后使用编程式路由 如果请求路径有重定向信息就按重定向跳转否则进入根路径
                            this.$router.push(redirectPath).catch(() => {})
                        })
                        .catch(() => {
                            //失败刷新按钮、验证码
                            this.loading = false
                            if (this.captchaEnabled) {
                                this.getCode()
                            }
                        })
                        .finally({})
                }
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.login {
    /*防止鼠标滚动页面出现上下空白区域 */
    position: fixed;
    /* 宽度为视口宽度（100% of viewport width） */
    width: 100vw;
    /* 高度为视口高度（100% of viewport height） */
    height: 100vh;
    /* 指定为弹性布局 */
    display: flex;
    /* 弹性布局水平主轴居中对齐*/
    justify-content: center;
    /* 弹性布局垂直交叉轴居中对齐*/
    align-items: center;
    background-image: url('@/assets/images/login-background.jpeg');
    background-size: cover;
}

.title {
    margin: 0px auto 30px auto;
    text-align: center;
    color: #707070;
}

/* 登录容器设置 */
.login-form {
    border-radius: 6px;
    background: #ffffff;
    width: 400px;
    padding: 25px 25px 5px 25px;

    /* 输入框高度调整 */
    .el-input {
        height: 38px;
    }
}

.login-code {
    @include border;
    border-radius: 6px;
    width: 33%;
    /*浮动到右边 */
    float: right;
    margin-left: 12px;

    img {
        height: 35px;
        /*鼠标停留在图片上的样式 */
        cursor: pointer;
        /*垂直居中 */
        vertical-align: middle;
    }
}

.login-code-img {
    width: 100%;
    height: 38px;
    display: inline-flex;
}

.el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
}
/* 媒体查询：屏幕宽度小于1024px */
@media (max-width: 1023px) {
    .login-form {
        width: 70%;
    }
    .inputCode {
        width: 60% !important;
    }
}
</style>
